Repository navigation
[lexical][lexical-clipboard][lexical-code-core][lexical-code-prism][lexical-code-shiki][lexical-eslint-plugin][lexical-extension][lexical-list][lexical-playground][lexical-react][lexical-table][lexical-y] Feature: flag accidental nested editor updates - #9106
ZedingZhang wants to merge 11 commits into
Conversation
|
Hi @ZedingZhang! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
etrepum
left a comment
There was a problem hiding this comment.
I think this should be configured by default at least locally in the repo to make sure it finds the issues we expect it to
7875b4d to
6dd24c0
Compare
|
Update: this status was superseded by the review fixes in ff5da9a. The cross-editor history rewrite and file-wide |
Here is an additional review from claude codeReviewThe rule idea is good and the implementation is tidy — extracting What I verified locally
Blocking1. The rule can't distinguish "this editor" from "a different editor", and the message tells you to do the wrong thing
editor.registerCommand(CMD, () => {
const nestedEditor = getNestedEditor();
nestedEditor.update(() => {}); // error: "Remove the nested nestedEditor.update wrapper"
return true;
}, 0);
export function $syncChild(childEditor: LexicalEditor) {
childEditor.update(() => {}); // error: "Remove the nested childEditor.update wrapper"
}Following that message would run the child's mutations against the parent's active context. The false positive is encoded as editor.registerNodeTransform(Node, node => {
nestedEditor.update(() => node.remove());
});The rule should only fire when the receiver is provably the same editor as the enclosing context (same identifier/binding), and treat a differently-named receiver as out of scope. 2. That false positive drove a test rewrite that loses coverage
The original built the child inside the parent's update via Worth noting: the same file still has 3.
|
6dd24c0 to
ff5da9a
Compare
|
Addressed the additional review in ff5da9a and rebased the branch onto the current
Validation on the rebased head: full lint, TypeScript, build, Prettier on changed files, all 6 ESLint 8/10 integration scenarios, 7 affected suites, and the full core unit project (311 files / 4,746 passed / 1 skipped). |
etrepum
left a comment
There was a problem hiding this comment.
I think it's fine to go ahead and make new rules opt-out, so long as the rules don't have a lot of false positives. Most of the value is in having defaults is to prevent as many errors as possible, not to be as backwards compatible as possible. Anyone that wants a configuration that's frozen in time shouldn't be using defaults.
That said, I don't think we're quite there yet with this.
Claude review
Reviewed at ff5da9a against merge base 1723cd1.
Verification: tsc -p . clean · eslint . clean · plugin unit tests 21/21 · lexical + lexical-react unit 1147/1147 (2 browser-mode files unrun locally — no Playwright browser) · lexical-list / lexical-clipboard / lexical-code-* 361/361.
The rule targets a real hazard — updateEditor pushes to editor._updates when editor._updating (LexicalUpdates.ts:1332), so source order really does diverge from execution order — and the identifier-binding comparison added in ff5da9a is the right shape. Four issues below are worth fixing before merge.
1. The read diagnostic gives advice that throws
editor.read is in implicitUpdateCallbackIndex, so this is reported:
editor.read(() => {
editor.update(() => {});
});
// editor.read callback already provides an update context for this editor.
// Remove the nested editor.update wrapper.A read callback is a read-only context, not an update context, and the nested update is the only thing that makes the write land. Following the message:
Error: Cannot use method in read-only mode.
❯ errorOnReadOnly packages/lexical/src/LexicalUpdates.ts:106:5
❯ $createParagraphNode packages/lexical/src/nodes/LexicalParagraphNode.ts:218:32
❯ EditorState.read packages/lexical/src/LexicalEditorState.ts:166:12
The PR already suppresses exactly this twice in LexicalEditor.test.tsx ("Nesting update in read works, although it is discouraged"). read needs its own messageId — something like "an update nested in read() is deferred until the read returns; move it after the read" — or should be dropped from the map. The README inherits the error: "This includes the callbacks passed to editor.update, editor.read, … already inside an update context".
Related false negative: read has a two-arg overload (read(mode, fn), LexicalEditor.ts:1848). The hardcoded callback index 0 misses editor.read('latest', () => editor.update(...)) — verified unreported.
2. Nested updates carrying options get "just remove the wrapper"
Verified against the rule:
editor.update(() => { editor.update(() => {}, {discrete: true}); });
// -> editor.update callback already provides an update context for this editor.
// Remove the nested editor.update wrapper.
editor.registerCommand(C, () => { editor.update(() => {}, {tag: 'history-merge'}); }, 1);
// -> same messageRemoving the wrapper silently drops discrete, tag, onUpdate, and skipTransforms. The PR itself hits this three times — two eslint-disables in FindReplaceExtension for {discrete: true}, and a hand-conversion to $addUpdateTag in useYjsCollaboration.
Suggestion: when node.arguments.length > 1, either skip the report or use a message that names the options and their in-context equivalents ($addUpdateTag, $onUpdate). {discrete: true} in particular is almost always deliberate and is a good candidate for a default exemption.
3. A $-named callback silences the same-editor check
getImplicitUpdateContext returns the dollarFunction context and never falls through to the editor-callback branch. Since isCurrentEditorInDollarFunction only accepts the literal names editor / $getEditor, any other editor variable escapes entirely:
// REPORTED
childEditor.update(() => { childEditor.update(() => {}); });
// NOT reported — the $ name shadows the editorCallback check
childEditor.update(function $inner() { childEditor.update(() => {}); });
// NOT reported
const $h = useCallback(() => { childEditor.update(() => {}); }, []);
childEditor.registerCommand(C, $h, 1);$-prefixed callbacks are idiomatic here ($onEscape in ImageComponent.tsx is one), so this hole is easy to hit in practice. When the dollarFunction check doesn't fire, fall through to the editorCallback check rather than returning early.
4. The new checkList test doesn't cover the change it justifies
packages/lexical-list/src/checkList.ts drops an editor.update() wrapper — a behavior change in a shipped package. Checking out the base checkList.ts and running the new test against it:
Test Files 1 passed (1)
Tests 7 passed (7)
It passes both ways, because $beginUpdate drains editor._updates synchronously before the DOM event handler returns, so event.preventDefault() was already in time. Either drop the test or reshape it to assert the ordering that actually changed.
Smaller items
useYjsCollaboration.tsx— the outereditor.updateininitializeEditoralready passes{tag: HISTORY_MERGE_TAG}, so the added$addUpdateTag(HISTORY_MERGE_TAG)and its import are dead. Androot1.isEmpty()is now provably always true: it sits insideif (root.isEmpty())with no intervening mutation. That re-check existed because the update was deferred; inlining makes it a dead guard. Existing collab tests (the bootstrapped initialEditorState can not be undone) do cover the callback path and pass, so this is cleanup rather than a correctness risk — but the guard removal should be deliberate, not incidental.- Commit subject —
[lexical-eslint-plugin] Feature: …, but the diff also changeslexical-listandlexical-react(shipped behavior) plus playground and examples.AGENTS.mdrequires the subject to name everypackages/directory the diff touches. isSameEditorExpressionhardcodes'$getEditor'in the zero-arg-call branch, so a user-configured accessor (isEditor: '^getMyEditor$') is recognized bygetEditorMethodbut can never match as "same editor" — silently inconsistent with what theisEditoroption advertises.this.editor.update(() => this.editor.update(...))is unreported —isSameEditorExpressionhas noThisExpressioncase. Cheap to add.getIdentifierVariablerewrite now scans every scope and every variable inscopeManagerand resolves viavariable.references, replacing the old parent-walk plusscope.setname fallback. That is a semantic change torules-of-lexical, not just a move: it resolves arbitrarily deep references the old version missed, and drops the name-based fallback. It reads as neutral-to-better and the existing rule tests pass, but it deserves a line in the description since it wasn't advertised as a behavior change. Both callers are gated (reportedSetinrules-of-lexical, candidate sites in the new rule), so the O(scopes × variables) scan isn't a practical concern.ImageComponent.tsxis fine as rewritten:setSelecteditself callseditor.update(useLexicalNodeSelection.ts:86), so the observable order ($setSelection(null)→focus()→ selection update) is unchanged.
Items 1–3 are rule bugs that will mislead adopters; 4 is a test that doesn't test. The rest are cleanups.
ff5da9a to
53a06de
Compare
|
Follow-up ( Addressed the latest review in
The smaller items are also addressed:
Validation on the rebased head:
Browser-mode and E2E suites were not run locally; the refreshed GitHub Actions matrix is starting on the new head. |
There was a problem hiding this comment.
This looks good. The rule targets a real hazard: a same-editor update() inside an update, command or transform callback is queued, so source order and execution order differ. The diagnostics now handle the cases raised in earlier review rounds: cross-editor receivers, both read() overloads, $-named callbacks, update options and this.editor. The repository rewrites keep their behavior (Find/Replace stays synchronous through $flushSyncAfterUpdate(), and the Yjs bootstrap keeps its empty-root guard and HISTORY_MERGE_TAG). All of the suggestions below are optional and non-blocking, except that the first will be needed before this can merge cleanly.
- Rebase onto current
mainand add two suppressions (eslint.config.mjs:351). Since this branch's merge base, #9219 added two intentional nested updates topackages/lexical/src/__tests__/unit/LexicalSelectionChangeCommand.test.ts, at lines 123 and 351 onmain. With the rule atERRORin the monorepo, lint on the merged tree reports both as errors. CONTRIBUTING.md asks that the code lints. Per-site// eslint-disable-next-line @lexical/no-nested-editor-updates -- …comments, like the ones inLexicalEditor.test.tsx, would fix it. - Fix the
readOnlyUpdatetiming claim (packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:496). The message says the nested update "is deferred until the read returns". Outside an update,updateEditorruns the update immediately becauseeditor._updatingis false: the callback runs inside the read and only its commit waits. Inside an update, the call waits until the enclosing update's callback ends. The advice is right; only the explanation needs changing. For example: "{{context}} is read-only and cannot observe {{callee}}; move the update after the read callback instead of removing its wrapper." - Mention convergence for transforms (
packages/lexical-eslint-plugin/README.md, "Preventing nested editor updates"). Today, an update queued from a transform runs after the transform pass, so its edits are not transformed. Without the wrapper, those edits are transformed again, and a mutation without a precondition will loop until Lexical's infinite-transform guard throws. One sentence pointing at the preconditions section ofdocs/concepts/transforms.mdwould cover it. - Nit: which receivers count as the active editor (
packages/lexical-eslint-plugin/README.md:106-107,:124). Inside$functions, configuredisEditorpatterns also count as the active editor, not onlyeditorand$getEditor(). The default/editor$/ialready matches zero-argument calls such asgetNestedEditor(), not only configured accessors.
Enabling the rule in the default presets follows the direction a maintainer gave earlier in this thread for rules with few false positives. Across packages/, examples/ and dev-examples/, every report I saw was a genuine same-editor or $-function nesting. The CI workflows for this head still need maintainer approval to run.
## Description Nested same-editor updates can run in a different order depending on whether their caller already has an active Lexical context. This makes command handlers and dollar functions difficult to reason about and can hide ordering bugs. Add the @lexical/no-nested-editor-updates rule, its public options type, RuleTester coverage, and consumer documentation. The rule recognizes direct callbacks that provide an update context and dollar functions that open their own update, while avoiding unrelated update methods. Extract the shared Lexical function-name helpers so both plugin rules use the same naming logic. The rule reports without autofixing because the safe rewrite depends on the call site. Closes meta#7040 ## Test plan ### Before ```text RuleTester nested-update fixture AssertionError: Should have 1 error but had 0: [] ``` ### After ```text corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts --run Test Files 1 passed (1) Tests 3 passed (3) ``` ```text corepack pnpm tsc corepack pnpm exec prettier --check packages/lexical-eslint-plugin Both commands exited successfully. ``` Browser-mode and E2E suites were not run locally because this commit changes only the ESLint plugin.
…de-shiki][lexical-history][lexical-list][lexical-playground][lexical-react] Chore: enable nested update lint locally ## Description Enable @lexical/no-nested-editor-updates as an error in the monorepo so new accidental nesting is caught during normal lint runs. Resolve the existing findings by removing redundant same-editor wrappers from callbacks that already have a Lexical context and by renaming helpers whose dollar prefix incorrectly promised that callers supplied one. Keep behavior-specific updates explicit where their call sites require separate timing or context. Closes meta#7040 ## Test plan ### Before ```text corepack pnpm lint ✖ 15 problems (15 errors, 0 warnings) ``` ### After ```text corepack pnpm lint 0 problems ``` ```text corepack pnpm vitest packages/lexical-history packages/lexical-list packages/lexical-clipboard packages/lexical-code-prism packages/lexical-code-shiki --run Test Files 36 passed (36) Tests 409 passed (409) ``` ```text corepack pnpm tsc corepack pnpm build Both commands exited successfully. ``` Browser-mode and E2E suites were not run locally; the pull request CI matrix covers them.
…al-playground][lexical-react] Bug Fix: avoid cross-editor false positives ## Description The initial rule treated updates to child editors as though they were nested updates on the active parent editor. Its generic diagnostic could therefore recommend a behavior-changing rewrite. Compare editor identifier bindings before reporting callback cases, preserve cross-editor history coverage and intentional discrete updates, and use separate guidance for dollar-function ownership. Add read callback detection, document the rule's local-analysis limits, share matcher and scope helpers with rules-of-lexical, and replace broad test-file exclusions with per-site suppressions. The shared identifier lookup now resolves references across the scope manager instead of relying on a parent-scope name fallback, which lets both rules distinguish shadowed bindings more consistently. Closes meta#7040 ## Test plan ### Before ```text RuleTester cross-editor fixture AssertionError: Should have no errors but had 1 ``` ### After ```text corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts packages/lexical-eslint-plugin/src/__tests__/unit/rules-of-lexical.test.ts packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx --run Test Files 7 passed (7) ``` ```text corepack pnpm vitest --project unit --no-watch Test Files 311 passed (311) Tests 4746 passed | 1 skipped (4747) ``` ```text corepack pnpm test-eslint-integration Total tests: 6 Passed: 6 ``` ```text corepack pnpm lint corepack pnpm tsc corepack pnpm build corepack pnpm exec prettier --check <changed files> All commands exited successfully. ``` Browser-mode and E2E suites were not run locally; the pull request CI matrix covers them.
…xical-react] Bug Fix: make nested update diagnostics safe ## Description Nested updates in read callbacks and updates carrying options received advice to remove a wrapper even when doing so would throw or discard behavior. Dollar-prefixed callback names could also hide the stronger same-editor callback check. Give read callbacks a read-only diagnostic that recommends moving the update, recognize both read overloads, and exempt calls with update options. Check direct editor callback ownership before dollar-function ownership, support configured zero-argument editor accessors, and compare this.editor across lexical arrow callbacks. Enable the rule as a warning in the default presets after reducing false positives. Remove obsolete suppressions, drop the checklist test that passed against both implementations, and remove the redundant Yjs bootstrap guard and tag operation identified in review. Closes meta#7040 ## Test plan ### Before ```text corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts --run Test Files 1 failed (1) Tests 3 failed | 1 passed (4) AssertionError: Should have no errors but had 4 AssertionError: Should have 1 error but had 0 ``` ### After ```text corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts --run Test Files 1 passed (1) Tests 4 passed (4) ``` ```text corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts packages/lexical-eslint-plugin/src/__tests__/unit/rules-of-lexical.test.ts packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx --run Test Files 7 passed (7) Tests 191 passed (191) ``` ```text corepack pnpm vitest --project unit --no-watch Test Files 312 passed (312) Tests 4776 passed | 1 skipped (4777) ``` ```text corepack pnpm test-eslint-integration Total tests: 6 Passed: 6 ``` ```text corepack pnpm lint corepack pnpm tsc corepack pnpm build corepack pnpm exec prettier --check <changed files> All commands exited successfully. ``` Browser-mode and E2E suites were not run locally; the pull request CI matrix covers them.
…e nested update options in context
## Description
The nested update rule skipped every call with an options argument, even though `tag`, `discrete`, and `onUpdate` can be applied to the active update context. This left actionable nested updates unreported and kept two nested `editor.update(..., {discrete: true})` calls in Find/Replace.
Report statically analyzable option objects when every option has an in-context helper, and name `$addUpdateTag`, `$flushSyncAfterUpdate`, or `$onUpdate` in the diagnostic. Continue to skip `skipTransforms` and opaque option bags because they cannot be migrated safely. Move Find/Replace command mutations into their existing command update and preserve synchronous commits with `$flushSyncAfterUpdate()`. Keep explicit lint suppressions only in core tests whose purpose is to exercise nested update behavior.
Closes meta#7040
## Test plan
### Before
With the two `$flushSyncAfterUpdate()` calls temporarily removed:
```text
$ corepack pnpm vitest --project unit --no-watch packages/lexical-playground/__tests__/unit/FindReplace.test.ts -t synchronously
❯ FindReplace.test.ts (55 tests | 2 failed | 53 skipped)
× REPLACE_CURRENT_COMMAND replaces the current match synchronously
Expected: "baz bar foo"
Received: "foo bar foo"
× REPLACE_ALL_COMMAND replaces all matches synchronously
Expected: "qux bar qux"
Received: "foo bar foo"
Test Files 1 failed (1)
Tests 2 failed | 53 skipped (55)
```
### After
```text
$ corepack pnpm vitest --project unit --no-watch packages/lexical-eslint-plugin/src/__tests__/unit packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx
Test Files 6 passed (6)
Tests 168 passed (168)
$ corepack pnpm test-eslint-integration
Total tests: 6
Passed: 6
✓ All tests passed!
$ corepack pnpm lint
> eslint ./
(exit 0)
$ corepack pnpm tsc
> tsc
(exit 0)
$ corepack pnpm build
> node scripts/build.mjs
(exit 0)
$ corepack pnpm exec prettier --check <changed files>
Checking formatting...
All matched files use Prettier code style!
```
Browser-mode and E2E suites were not rerun locally; GitHub Actions will exercise those matrices on the pushed head.
…g Fix: adapt nested update lint to ESM ## Description The nested-update rule and its shared utilities still used CommonJS after the plugin sources moved to ESM in meta#9127. Export those modules as ESM, verify the rule through both the default plugin and its module namespace, and check the current flat presets and their aliases instead of the removed legacy preset. Update the configuration documentation and rename three newly added upstream test helpers that open their own editor updates, preserving their discrete updates and history tags. ## Test plan ### Before ```text $ node -e "import('./packages/lexical-eslint-plugin/src/LexicalEslintPlugin.js')" SyntaxError: The requested module '../util/ruleOptions.js' does not provide an export named 'DEFAULT_DOLLAR_FUNCTION_MATCHER' $ node node_modules/vitest/vitest.mjs run --project unit packages/lexical-eslint-plugin/src/__tests__/unit TypeError: Cannot read properties of undefined (reading 'rules') Test Files 1 failed | 3 passed (4) Tests 1 failed | 19 passed (20) ``` After rebasing onto the latest main, the newly added table test helper also failed the enabled rule: ```text $ corepack pnpm lint packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts 74:3 error $withEditor is named as a Lexical $function but calls editor.update @lexical/no-nested-editor-updates ✖ 1 problem (1 error, 0 warnings) ``` ### After ```text $ corepack pnpm vitest --project unit --no-watch packages/lexical-eslint-plugin/src/__tests__/unit packages/lexical-clipboard/src/__tests__/unit/ClipboardImportExtension.test.ts packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-extension/src/__tests__/unit/HMRExtension.test.ts packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts packages/lexical/src/__tests__/unit/Issue4815Repro.test.ts Test Files 13 passed (13) Tests 283 passed (283) ``` ```text $ corepack pnpm lint $ corepack pnpm tsc $ corepack pnpm tsc-scripts $ corepack pnpm tsc-extension $ corepack pnpm tsc-website $ corepack pnpm prettier $ corepack pnpm build All commands exited successfully. ``` The ESLint integration script could not be rerun on native Windows because it launches `/bin/bash`; the refreshed GitHub Actions workflow covers it. Browser-mode and E2E suites were not run locally and are also covered by the pull request CI matrix.
…ation ## Description Keep rules-of-lexical's original declaration lookup and resolve editor receiver references only in no-nested-editor-updates. Remove the shared whole-scope scanner, duplicated diagnostic construction, and the SourceCode fallback for ESLint 8, which is outside the declared peer range. Shorten repeated README examples while retaining the supported patterns and analysis limits. The existing diagnostics, presets, repository activation, migration changes, and regression tests are preserved. Individual migration reversions and a missing-flush mutation established which changes must remain. ## Test plan ### Before Ablation control: temporarily reusing the original declaration lookup for receiver references misses six of fourteen probe cases. The existing plugin tests also detect the regression: ```text $ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit Test Files 1 failed | 3 passed (4) Tests 2 failed | 18 passed (20) ``` ### After ```text $ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-extension/src/__tests__/unit/HMRExtension.test.ts packages/lexical/src/__tests__/unit/Issue4815Repro.test.ts packages/lexical-code-prism/src/__tests__/unit/LexicalCodeNodeTabs.test.ts packages/lexical-code-shiki/src/__tests__/unit/LexicalCodeNodeTabs.test.ts packages/lexical-clipboard/src/__tests__/unit/ClipboardImportExtension.test.ts packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts Test Files 15 passed (15) Tests 451 passed (451) $ pnpm exec npm-run-all --parallel tsc tsc-scripts tsc-extension tsc-website prettier lint (exit 0) $ node node_modules/flow-bin/cli.js full-check --max-workers 4 Found 0 errors $ pnpm run build (exit 0) $ git diff --check (exit 0) ``` The new rule's diagnostics match the original PR head in 798 JavaScript/TypeScript cases; twelve existing-rule cases match the merge base, including fix/suggestion payloads. Published-build smoke checks pass for ESLint 9 and 10: the original valid/invalid fixtures and an additional nested-update fixture, six scenarios total. On Windows/Node 24, the unchanged ci-check Flow launcher fails with spawn EINVAL when spawning flow.cmd. The checks above run its static-check commands directly and invoke the native Flow CLI. Browser and E2E matrices were not run.
…x: finish nested-update review follow-ups ## Description After rebasing onto main at dfe058a, the repository-wide nested-update rule reports nine findings in newly added code. Add per-site exemptions for tests of nested update ordering and error recovery, and for the collaboration self-check's separate verification editor. Rename the block-container test helpers that own their update context or only manipulate strings. Make the read-only diagnostic describe the required move while preserving the update wrapper and options. Document transform convergence and the configured editor matchers and default zero-argument accessors. Add the changeset required by the current repository guidelines for this PR. ## Test plan ### Before ```text $ pnpm run lint ✖ 9 problems (9 errors, 0 warnings) [ELIFECYCLE] Command failed with exit code 1. ``` ```text $ pnpm run check-changesets -- --base upstream/main Changeset check found 1 problem(s): - This pull request changes published code without a changeset for: @lexical/eslint-plugin @lexical/list @lexical/react ``` ### After ```text $ pnpm run ci-check Changeset check passed: 101 pending changeset(s) valid. Found 0 errors (exit 0) $ pnpm run build (exit 0) $ pnpm run test-eslint-integration Total tests: 4 Passed: 4 ``` ```sh pnpm exec vitest run --project unit --maxWorkers=4 \ packages/lexical-eslint-plugin/src/__tests__/unit \ packages/lexical-playground/__tests__/unit/FindReplace.test.ts \ packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx \ packages/lexical/src/__tests__/unit/LexicalSelectionChangeCommand.test.ts \ packages/lexical/src/__tests__/unit/LexicalUpdateErrors.test.ts \ packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx \ packages/lexical-list/src/__tests__/unit/checkList.test.tsx \ packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx \ packages/lexical-extension/src/__tests__/unit/HMRExtension.test.ts \ packages/lexical-extension/src/__tests__/unit/BlockContainers.test.ts \ packages/lexical/src/__tests__/unit/Issue4815Repro.test.ts \ packages/lexical-code-prism/src/__tests__/unit/LexicalCodeNodeTabs.test.ts \ packages/lexical-code-shiki/src/__tests__/unit/LexicalCodeNodeTabs.test.ts \ packages/lexical-clipboard/src/__tests__/unit/ClipboardImportExtension.test.ts \ packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts \ packages/lexical-y/src/__tests__/unit/regressions/RemoteReadAppEdits.test.ts \ packages/lexical-y/src/__tests__/unit/SelfCheckBuilder.test.ts \ packages/lexical-y/src/__tests__/unit/FollowUpTextFields.test.ts \ packages/lexical-y/src/__tests__/unit/regressions/FollowUps.test.ts ``` ```text Test Files 22 passed (22) Tests 1030 passed | 1 expected fail (1031) ``` The expected-failure case uses test.fails in FollowUps.test.ts. Additional published-plugin probes pass on ESLint 9 and 10 for cross-editor updates, same-editor nesting, and the exact read-only diagnostic with update options (three probes per major). Browser-mode and E2E validation is pending CI.
977e24b to
f9abf67
Compare
There was a problem hiding this comment.
Thanks for working through all the review rounds. The rule's diagnostics now match how Lexical queues same-editor updates, and the repository rewrites (checklist Space handler, Yjs initial state, Find/Replace with $flushSyncAfterUpdate(), playground commands) keep their behavior. The earlier notes on the read-only message, the LexicalSelectionChangeCommand.test.ts suppressions and the README's isEditor wording are all addressed.
Needs a change
packages/lexical-eslint-plugin/src/rules/rules-of-lexical.js:189: this PR deletes thegetSourceCode(context)helper thatmainkeeps with the comment “kept for ESLint 8 compat”, and readscontext.sourceCodedirectly. ESLint 8 releases before 8.40 have nocontext.sourceCode, sorules-of-lexicalnow throwsCannot read properties of undefined (reading 'scopeManager')on its first report instead of warning: under ESLint 8.39 the base rule reports normally and the head rule throws; under 8.40 both work. The new rule doesn't need this cleanup, and the backwards-compatibility section of AGENTS.md asks to keep existing behavior intact when in doubt. Please keep the fallback, for example by exporting agetSourceCodehelper fromutil/ruleOptions.jsnext toparseMatcherOptionand using it in both rules.
Optional, non-blocking
packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:419: the rule doesn't look atasync, so an async command listener or transform that awaits and then callseditor.update(...)is told to remove the wrapper, although code after anawaithas already left the outer update. Returning early when the enclosing function isasyncwould avoid that advice.
…ip async update contexts ## Description Restore the shared getSourceCode(context) fallback used by both rules so ESLint 8.39 reports diagnostics instead of throwing. Keep the modern sourceCode path for ESLint 9 and 10, and preserve fix and suggestion payloads in a regression test. Skip async enclosing functions in no-nested-editor-updates because an await can end the active editor context. Continue checking synchronous editor callbacks nested inside async functions. Cover command listeners, transforms, both read overloads, update callbacks and dollar functions, and document the conservative boundary. ## Test plan ### Before With the new regression tests on the previous implementation: ```text $ pnpm exec vitest run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit TypeError: Cannot read properties of undefined (reading 'scopeManager') TypeError: Cannot read properties of undefined (reading 'getScope') Test Files 2 failed | 3 passed (5) Tests 3 failed | 20 passed (23) ``` Real ESLint 8.39.0, 8.40.0, 9.39.5 and 10.14.0 smoke cases covering diagnostics, fixes, valid functions and async/sync update boundaries: ```text $ node ../eslint-compat/smoke.mjs 10 passed, 10 failed ``` ### After ```text $ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit Test Files 5 passed (5) Tests 23 passed (23) $ pnpm run ci-check Changeset check passed: 101 pending changeset(s) valid. Found 0 errors (exit 0) $ pnpm run build (exit 0) $ node packages/lexical-eslint-plugin/__tests__/integration/integration-test.mjs Total tests: 4 Passed: 4 $ node ../eslint-compat/smoke.mjs "$PWD/packages/lexical-eslint-plugin/dist/LexicalEslintPlugin.js" 20 passed, 0 failed $ git diff --check (exit 0) ``` Validated on macOS / Node 26. Browser-mode and E2E matrices were not run for this ESLint-only follow-up.
There was a problem hiding this comment.
This looks good to me. Restoring getSourceCode() as a shared helper fixes the ESLint 8 regression from the last round. Async callbacks are now skipped, and the LexicalSelectionChangeCommand.test.ts suppressions and the README's isEditor wording are in. The rewrites in @lexical/list, @lexical/react and the playground keep their update tags and commit timing. The updated Find/Replace tests fail if $flushSyncAfterUpdate() is removed, so they really guard the synchronous commit.
The GitHub workflows for this head are still waiting for approval, so CI hasn't run yet.
Optional, non-blocking
-
packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:213:SourceCode#getScope()only exists from ESLint 8.37. On 8.0–8.36, the rule throwssourceCode.getScope is not a functionforeditor.update(() => { editor.update(() => {}); }), even with the restoredgetSourceCode()fallback. On 8.37 it reports normally.eslint >=9is the declared peer range, so this doesn't block. But the changeset says both rules keep the ESLint 8 fallback, and AGENTS.md's backwards-compatibility section asks to assume people rely on current behavior. Either resolve the reference throughsourceCode.scopeManagerwhengetScopeis missing, asgetIdentifierVariableinrules-of-lexical.jsdoes, or scope that changeset sentence to ESLint 8.37+. -
packages/lexical-eslint-plugin/src/__tests__/unit/sourceCodeCompatibility.test.ts:42: the fake legacy context returns ESLint 10'sSourceCode, which already hasgetScope(), so this test can't catch the case above. RemovinggetScopefrom the returned object as well would cover it. -
packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:490: inside a$function, any receiver namededitoris taken to be the active editor. That is why$followUpDifferenceinpackages/lexical-y/src/internal/SelfCheck.tsneeded a suppression: its localeditoris a separate verification editor, so "remove the update wrapper" would be wrong there. Conditioning the whole message, say "If {{callee}} targets the editor this $function runs in, remove the update wrapper, or remove the $ prefix if this function intentionally starts the update", would keep the advice safe when the heuristic misfires. - Nit: for
registerNodeTransform, the README's note that inline mutations re-enter the transform cycle isn't in the diagnostic itself. A transform-specific message could point to the preconditions docs.
…rify nested update advice ## Description The nested-update rule throws on ESLint 8.0-8.36 because those SourceCode objects have no getScope method. Resolve identifier references through scopeManager when the method is absent, preserving binding identity for shadowed editor variables. The compatibility regressions now exercise both legacy SourceCode shapes and compare diagnostics, fixes and suggestions. Condition both $function diagnostics on the receiver targeting the active editor before recommending wrapper removal or option migration. Give node transforms separate diagnostics that link to convergence preconditions, including when an update has options. ## Changeset Updated .changeset/no-nested-editor-updates.md with the scope-manager fallback and the conditional ownership and transform guidance. ## Test plan ### Before New regressions against the previous implementation: ```text $ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit TypeError: sourceCode.getScope is not a function Test Files 2 failed | 3 passed (5) Tests 8 failed | 27 passed (35) ``` ### After ```text $ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit Test Files 5 passed (5) Tests 35 passed (35) $ pnpm run ci-check Changeset check passed: 101 pending changeset(s) valid. Found 0 errors (exit 0) $ pnpm run build (exit 0) $ node packages/lexical-eslint-plugin/__tests__/integration/integration-test.mjs Total tests: 4 Passed: 4 $ git diff --check (exit 0) ``` A separate smoke harness against the built plugin passed 17 cases on each of ESLint 8.0.0, 8.36.0, 8.37.0, 8.39.0, 8.40.0, 9.39.5 and 10.14.0. It compares diagnostics, locations, fixes and suggestions across versions, excluding the nodeType field removed by ESLint 10. Cases include resolved, unresolved and shadowed editor bindings, cross-editor updates, transform and $function guidance with options, both read overloads and async contexts. Validated on macOS with Node 26. Browser-mode and E2E matrices were not run for this ESLint-only follow-up.
There was a problem hiding this comment.
This looks good to me. The scopeManager fallback makes the rule work on ESLint 8 before 8.37. Loaded into real ESLint 8.0.0, 8.27.0 and 8.36.0 Linters, it gives the same diagnostics as 8.37.0 and 10.11.0 across same-binding, shadowed, cross-editor, $function, transform, read and async cases. The new compatibility tests also fail against the previous version of the rule, so they guard the fix. The conditional $function wording and the transform message with the preconditions link cover the earlier suggestions. The @lexical/list, @lexical/react and playground rewrites keep their update tags and commit timing, and the Find/Replace tests still fail if $flushSyncAfterUpdate() is removed.
The GitHub workflows for this head are still waiting for approval, so CI hasn't run yet.
Optional, non-blocking suggestions
- When you rebase onto current
main: #9862 added a$retokenizeOldTokenshelper that opens its owneditor.update(…, {discrete: true}). It lives inpackages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts(line 816 onmain) andpackages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts(line 840). Sinceeslint.config.mjs:351sets this rule toerror, lint on the merged tree reports both, and nothing else. Renaming the helper toretokenizeOldTokens(three call sites per file) keeps lint green, as this PR already does forpasteHtmlandrunOutdentScenario. AGENTS.md's "$Functions Convention" reserves the prefix for functions that run inside an existing update or read. - Nit,
packages/lexical-eslint-plugin/src/index.ts:27and:39: the new keys on the exportedFlatConfig.rulesandPlugin.rulesinterfaces are required. An object that someone annotates asFlatConfigorPluginwith only the old keys would stop type checking, which.changeset/README.md("Type signature changes") counts as breaking. Marking the two new keys optional (?:) avoids that.
| lexicalPlugin.configs['flat/all'], | ||
| { | ||
| rules: { | ||
| '@lexical/no-nested-editor-updates': ERROR, |
There was a problem hiding this comment.
Optional, for the rebase: #9862 on main added a $retokenizeOldTokens helper that opens its own editor.update(…, {discrete: true}), in packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts (line 816) and packages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts (line 840). With this ERROR, lint on the head merged into current main reports both, and nothing else. Renaming the helper to retokenizeOldTokens (three call sites per file), as this PR does for pasteHtml and runOutdentScenario, keeps it green.
| '@lexical': Plugin; | ||
| }; | ||
| rules: { | ||
| '@lexical/no-nested-editor-updates': 'warn' | 'error' | 'off'; |
There was a problem hiding this comment.
Nit: this key, and 'no-nested-editor-updates' on Plugin.rules at line 39, are required. An object someone annotates as FlatConfig or Plugin with only the old keys would stop type checking, which .changeset/README.md ("Type signature changes") counts as breaking. Marking the two new keys optional (?:) avoids that.
Resolved packages/lexical-eslint-plugin/src/LexicalEslintPlugin.js: kept both rule typedefs, this branch's '@lexical/no-nested-editor-updates' and main's '@lexical/y-collab-status'.
|
Merged latest Conflict: Resolution: kept both, in alphabetical order. No behaviour change; the Verified: full |
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/y
@lexical/yjs
commit: |
There was a problem hiding this comment.
Thanks for this, the change looks good. The rule's advice matches how Lexical runs same-editor updates: command listeners already run inside an update for their editor, and a nested update drains into the same pending state. The cleanups in @lexical/list and @lexical/react commit the same state, tags and timing as before. Turning the rule on as a warning in the default presets follows the maintainer direction from the earlier review.
Needed before merge (CI):
packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts:816andpackages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts:840: the$retokenizeOldTokenshelper that came in with the latest merge ofmain(#9862) opens its owneditor.update(…, {discrete: true}). This PR's own rule, set toerrorineslint.config.mjs, reports both calls, sopnpm run lintand thecore-tests / integrityjob fail. Rename the helper toretokenizeOldTokens(the definition plus three call sites in each file), as this PR already does forpasteHtmlandrunOutdentScenario; both files then lint clean. AGENTS.md lists bothpnpm run lintandpnpm run ci-check(which runs ESLint) under Code Quality.
Optional, non-blocking:
packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:113(getUpdateOptionMigrations): the options diagnostic looks only at keys. Soeditor.update(fn, {discrete: isSync})is told to apply$flushSyncAfterUpdateunconditionally, which would force a synchronous commit whenisSyncis false. The README already says to call it only whendiscreteis true. Saying so in the message, or skipping non-literaldiscretevalues, would carry that caveat into the diagnostic.
The two Find/Replace …synchronously tests do pin the preserved synchronous commit: without the $flushSyncAfterUpdate() calls in FindReplaceExtension/index.tsx they fail, and with them they pass.
|
Heads-up on the
It deliberately wraps The branch is otherwise mergeable and its unit tests are green (36330 passed / 0 failed, against 36311 / 0 on |
|
I'll run a full review to re-check this with your note. |
Description
Nested
editor.update()calls on the same editor are queued while that editor is updating, so source order can differ from execution order. This adds@lexical/no-nested-editor-updatesas a warning in the default flat presets and an error in the monorepo.The rule compares receiver expressions and identifier bindings in direct
update,registerCommand, andregisterNodeTransformcallbacks, preserving valid cross-editor updates. Bothreadoverloads receive a separate diagnostic that keeps the update wrapper and moves the update after the read. Dollar-prefixed helpers receive guidance about owning their editor context, with wrapper removal and option migration explicitly conditioned on targeting the active editor. Transform diagnostics link to the preconditions needed for inline mutations to converge. Statically knowntag,discrete, andonUpdateoptions receive guidance using$addUpdateTag,$flushSyncAfterUpdate, and$onUpdate;skipTransformsand opaque option bags remain conservatively ignored. There is no autofix.Async callbacks and async dollar functions are skipped because an
awaitcan end the active editor context. Synchronous editor callbacks nested inside async functions are still checked. Aliases, callbacks passed by reference, and another nested callback layer remain outside the analysis.The plugin uses ESM sources, named exports, and flat configurations.
recommended,all, and theirflat/*aliases enable the rule. Both rules use a sharedgetSourceCode(context)helper that retains the existing ESLint 8 method fallback while usingcontext.sourceCodeon modern ESLint. The new rule resolves receiver references through ESLint's scope/reference API, falling back toscopeManagerwhenSourceCode#getScopeis unavailable before ESLint 8.37; the existingrules-of-lexicaldeclaration lookup is preserved.Repository cleanups preserve update options and existing cross-editor history coverage:
$flushSyncAfterUpdate()to preserve synchronous commits.HISTORY_MERGE_TAG.Closes #7040
Changeset
.changeset/no-nested-editor-updates.mdcovers the new rule, its conservative async boundary, legacy scope lookup, conditional editor-ownership and transform guidance, and repository behavior changes.Test plan
Before
The new regressions reproduce the pre-8.37 scope lookup crash and assert the conditional dollar-function and transform guidance:
After
Validated on
eac3d467with macOS / Node 26:Additional smoke checks against the built plugin pass on actual ESLint 8.0.0, 8.36.0, 8.37.0, 8.39.0, 8.40.0, 9.39.5, and 10.14.0: 17 cases per version covering resolved, unresolved and shadowed editor bindings, cross-editor updates, transform and dollar-function guidance with options, both read overloads, async contexts, and the existing rule's fixes and suggestions. The cross-version comparison includes diagnostic locations and fix/suggestion payloads, excluding only the
nodeTypefield removed by ESLint 10.The committed compatibility regressions compare the full diagnostic payloads with and without
context.sourceCode, and with and withoutSourceCode#getScope. They include function- and block-scoped shadowing so the legacy fallback cannot silently change which editor bindings match.Browser-mode and E2E matrices were not run locally for this ESLint-only follow-up.